package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntityImpl;
import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/my")
@Slf4j
public class MyActivityController {
    @GetMapping("/start")
    public String start(String userId) {
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        RuntimeService runtimeService = processEngine.getRuntimeService();
        String instanceKey = "My";
        log.info("开启请假流程...");
        Map<String, Object> map = new HashMap<String, Object>();
        //在holiday.bpmn中,填写请假单的任务办理人为动态传入的userId,此处模拟一个id
        map.put("userId", userId);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(instanceKey, map);
        TaskService taskService = processEngine.getTaskService();
        String instanceId = instance.getId(); // 任务ID
        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        String name = task.getName();
        msg = msg + "当前状态:" + name + "\n流程实例ID:" + instance.getId() + "\n";
        log.info(msg);
//        log.info("启动流程实例成功:"+ instance);
//        log.info("流程实例ID:"+instance.getId());
//        log.info("流程定义ID:"+instance.getProcessDefinitionId());
        return msg;
    }

    @GetMapping("/apply")
    public String apply(String id, String userId, String reason,@RequestParam(required = false) String assignee) {
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID
        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        if (task == null) {
            msg += "任务ID" + instanceId + "查询到任务为空！";
            log.info(msg);
            return msg;
        }
        String preName = task.getName();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("reason", reason);
        taskService.setVariablesLocal(task.getId(),map);
        taskService.setAssignee(task.getId(),assignee);
        taskService.complete(task.getId(),map);

        Task postTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        String postName = postTask.getName();
        msg += "状态变化：" + preName + "->" + postName + "\n申请理由：" + reason;
        log.info(msg);
        return msg;
    }

    @GetMapping("/show")
    public String show(String id) {
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID

        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        String days = (String) taskService.getVariable(task.getId(), "days");
        Date date = (Date) taskService.getVariable(task.getId(), "date");
        String reason = (String) taskService.getVariable(task.getId(), "reason");
        String userId = (String) taskService.getVariable(task.getId(), "userId");
        msg += "请假天数:  " + days + "\n";
        msg += "请假理由:  " + reason + "\n";
        msg += "请假人id:  " + userId + "\n";
        msg += "请假日期:  " + date.toString() + "\n";
        log.info(msg);
        return msg;
    }

    @GetMapping("audit")
    public String audit(String id, Integer agree, String reason,@RequestParam(required = false) String assignee) {
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID
        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        if (task == null) {
            return "任务结束或不存在";
        }
        String preName = task.getName();
        String userId = (String) taskService.getVariable(task.getId(), "userId");
        String lastReason = (String) taskService.getVariable(task.getId(), "reason");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("agree", agree);
        map.put("userId", userId);
        map.put("reason", reason);
        taskService.setVariablesLocal(task.getId(),map);
        taskService.setAssignee(task.getId(),assignee);
        taskService.complete(task.getId(), map);
        Task postTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        String postName=postTask==null?"":postTask.getName();
        msg += (agree == 1 ? "同意" : "拒绝") + "\n状态变化：" + preName + "->" + postName + "\n上级意见：" + lastReason + "->我的意见：" + reason;
        log.info(msg);
        return msg;
    }

    @GetMapping("/showList")
    public String showList(String id) {
        String instanceId = id; // 任务ID
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        HistoryService historyService = processEngine.getHistoryService();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).includeTaskLocalVariables().includeProcessVariables().orderByHistoricTaskInstanceStartTime().asc().list();
        List<HistoricVariableInstance> variableInstances = historyService.createHistoricVariableInstanceQuery().processInstanceId(instanceId).list();
        for (HistoricTaskInstance historicTaskInstance : list) {
            String name = historicTaskInstance.getName();
            String reason = (String) historicTaskInstance.getTaskLocalVariables().get("reason");
            String userId = (String) historicTaskInstance.getTaskLocalVariables().get("userId");
            msg += "name:" + name + ",reason:" + reason + ",userId:" + userId + "\n";
        }
        return msg;
    }

    @GetMapping("/showList3")
    public String showList2(String assignee) {
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        HistoryService historyService = processEngine.getHistoryService();
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).list();
        for (Task task : list) {
            String name = task.getName();
            String id = task.getId();
            msg+="name:"+name+"\n"+"id:"+id;
        }
        return msg;
    }

    @GetMapping("/showList2")
    public String showList3(String id) {
        String instanceId = id; // 任务ID
        String msg = "";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        HistoryService historyService = processEngine.getHistoryService();
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(instanceId).finished().orderByHistoricActivityInstanceStartTime().asc().list();
        List<HistoricTaskInstance> historicTaskInstances= historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).includeTaskLocalVariables().includeProcessVariables().orderByHistoricTaskInstanceStartTime().asc().list();        Map<String,HashMap<String,String>> map=new HashMap<>();
        for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
            String taskId = historicTaskInstance.getId();
            String reason = (String) historicTaskInstance.getTaskLocalVariables().get("reason");
            String userId = (String) historicTaskInstance.getTaskLocalVariables().get("userId");
            HashMap<String,String> params=new HashMap<>();
            params.put("reason",reason);
            params.put("userId",userId);
            map.put(taskId,params);
        }
        for (HistoricActivityInstance instance : list) {
            String taskId = instance.getTaskId();
            HashMap<String, String> params = Optional.ofNullable(map.get(taskId)).orElse(new HashMap<>());
            String name = instance.getActivityName();
            String reason = params.get("reason");
            String userId = params.get("userId");
            msg += "name:" + name + (reason==null?"":",reason:" + reason) + (userId==null?"":",userId:" + userId )+ "\n";
        }
        return msg;
    }


}
